package com.choosefine.it.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import com.choosefine.it.mobile.equipment.dto.ShoppingIdentityDTO;
import com.choosefine.it.base.dto.DateDTO;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.DateUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 11.18dzq 内部请求类
 * @author Administrator
 *
 */
public class HttpServiceBean {
	
	private CustomRestTemplate restTempLate = new CustomRestTemplate();
	private HttpHeaders headers = new HttpHeaders();
	private ObjectMapper om = new ObjectMapper();
	
	/**
	 * 11.18dzq
	 * @param url 访问地址
	 * @param params 参数
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String postRequestBody(String url,Object params) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException{
		Map data = om.readValue(om.writeValueAsString(params), Map.class);//将数据转换为map
		headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
		String s=om.writeValueAsString(data);
		HttpEntity request=new HttpEntity(s,headers);
		String result = restTempLate.postForObject(url, request, String.class);
		return result;
	}
	
	/**
	 * 11.23dzq
	 * @param url 访问地址
	 * @param params 参数
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	public String getRequestBody(String url,Object params) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException{
		String result=restTempLate.getForObject(url, String.class, params);
		return result;
	}
	
	/**
	 * 2016.1212 dzq 链接与参数拼接
	 * 
	 * @param url
	 * @param map
	 */
	public void urlFormat(StringBuffer url, Map<String, Object> map) {
		if (map != null) {
			Iterator<String> mapFor = map.keySet().iterator();
			int num = 1;
			while (mapFor.hasNext()) {
				String key = mapFor.next();
				Object mapCont = map.get(key) == null ? "" : map.get(key);
				if (num == 1) {
					url.append("?" + key + "=" + mapCont.toString());
				} else {
					url.append("&" + key + "=" + mapCont.toString());
				}
				num++;
			}
		}
	}
	
	/**
	 * 2016.1212 dzq 链接与参数拼接 -1参数不传递
	 * @param url
	 * @param map
	 */
	public void urlFormat(StringBuffer url,Map<String,Object> map,PageDTO page,DateDTO date,ShoppingIdentityDTO entityDto){
		int num=1;
		if(map!=null){
			Iterator<String> mapFor =map.keySet().iterator();
			while(mapFor.hasNext()){
				String key=mapFor.next();
				Object mapCont=map.get(key);
				boolean is=false;
				is= map.get(key) instanceof Integer?!"-1".equals(mapCont.toString()):true;//判断是否是数字，如是数字判断是否=-1
				if(mapCont!=null&&is&&!"".equals(map.get(key))){
					if(num==1){
						url.append("?"+key+"="+mapCont.toString());
					}else{
						url.append("&"+key+"="+mapCont.toString());
					}
					num++;
				}
			}
		}
		if(entityDto !=null){//身份
			if(num==1){
				url.append("?"+"userCode=" + (StringUtils.isEmpty(entityDto.getUserCode()) ? "" : entityDto.getUserCode()));
				url.append("&"+"projectCode="+entityDto.getProjectCode());
				if(entityDto.getTeamId()!=null&&entityDto.getTeamId()!=-1){//-1参数不传递 APP约定
					url.append("&"+"teamId="+entityDto.getTeamId());
				}
			}else{
				if (!StringUtils.isEmpty(entityDto.getUserCode())) {
					url.append("&" + "userCode=" + entityDto.getUserCode());
				}
				if (StringUtils.isEmpty(entityDto.getProjectCode())) {
					url.append("&" + "projectCode=" + entityDto.getProjectCode());
				}
				if(entityDto.getTeamId()!=null&&entityDto.getTeamId()!=-1){//-1参数不传递 APP约定
					url.append("&"+"teamId="+entityDto.getTeamId());
				}
			}
			num++;
		}
		if(date !=null){
			if(num==1){
				url.append("?"+"startTime="+date.getStartTime());
				url.append("&"+"endTime="+date.getEndTime());
			}else{
				url.append("&"+"startTime="+date.getStartTime());
				url.append("&"+"endTime="+date.getEndTime());
			}
			num++;
		}
		if(page != null){
			if(num==1){
				url.append("?"+"pageNum="+page.getPageNum());
				url.append("&"+"pageSize="+page.getPageSize());
			}else{
				url.append("&"+"pageNum="+page.getPageNum());
				url.append("&"+"pageSize="+page.getPageSize());
			}
		}
	}
	
	/**
	 * 2016.1212 dzq 商城链接与参数拼接 及 日期转换 eg: 2016-01-01 12：03：56
	 * @param url
	 * @param map
	 */
	public void shopUrlFormat(StringBuffer url,Map<String,Object> map,PageDTO page,DateDTO date){
		int num=1;
		if(map!=null){
			Iterator<String> mapFor =map.keySet().iterator();
			while(mapFor.hasNext()){
				String key=mapFor.next();
				Object mapCont=map.get(key);
				boolean is=false;
				is = map.get(key) instanceof Integer ? !"-1".equals(mapCont.toString()) : true;// 判断是否是数字，如是数字判断是否=-1
				if (mapCont != null && is && !"".equals(map.get(key))) {
					if(num==1){
						url.append("?"+key+"="+mapCont.toString());
					}else{
						url.append("&"+key+"="+mapCont.toString());
					}
					num++;
				}
			}
		}
		if(date !=null){
			if(num==1){
				url.append("?"+"startTime="+DateUtils.dateFomart(date.getStartTime()));
				url.append("&"+"endTime="+DateUtils.dateFomart(date.getEndTime()));
			}else{
				url.append("&"+"startTime="+DateUtils.dateFomart(date.getStartTime()));
				url.append("&"+"endTime="+DateUtils.dateFomart(date.getEndTime()));
			}
			num++;
		}
		if(page != null){
			if(num==1){
				url.append("?"+"pageNum="+page.getPageNum());
				url.append("&"+"pageSize="+page.getPageSize());
			}else{
				url.append("&"+"pageNum="+page.getPageNum());
				url.append("&"+"pageSize="+page.getPageSize());
			}
		}
	}
	
	/**
	 * 2016.1222 dzq 商城链接与参数拼接
	 * @param url
	 * @param map
	 */
	public void shopUrlFormat(StringBuffer url,Map<String,Object> map,PageDTO page,DateDTO date,ShoppingIdentityDTO entityDto){
		int num=1;
		if(map!=null){
			Iterator<String> mapFor =map.keySet().iterator();
			while(mapFor.hasNext()){
				String key=mapFor.next();
				Object mapCont=map.get(key);
				boolean is=false;
				is= map.get(key) instanceof Integer?!"-1".equals(mapCont.toString()):true;//判断是否是数字，如是数字判断是否=-1
				if(mapCont!=null&&is&&!"".equals(map.get(key))){
					if(num==1){
						url.append("?"+key+"="+mapCont.toString());
					}else{
						url.append("&"+key+"="+mapCont.toString());
					}
					num++;
				}
			}
		}
		
		if(entityDto !=null){//身份
			if(num==1){
				url.append("?"+"userCode="+entityDto.getUserCode());
				url.append("&"+"projectCode="+entityDto.getProjectCode());
				if(entityDto.getTeamId()!=null&&entityDto.getTeamId()!=-1){//-1参数不传递 APP约定
					url.append("&"+"teamId="+entityDto.getTeamId());
				}
			}else{
				url.append("&"+"userCode="+entityDto.getUserCode());
				url.append("&"+"projectCode="+entityDto.getProjectCode());
				if(entityDto.getTeamId()!=null&&entityDto.getTeamId()!=-1){//-1参数不传递 APP约定
					url.append("&"+"teamId="+entityDto.getTeamId());
				}
			}
			num++;
		}
		if(date !=null){
			if(num==1){
				url.append("?"+"startTime="+DateUtils.dateFomart(date.getStartTime()));
				url.append("&"+"endTime="+DateUtils.dateFomart(date.getEndTime()));
			}else{
				url.append("&"+"startTime="+DateUtils.dateFomart(date.getStartTime()));
				url.append("&"+"endTime="+DateUtils.dateFomart(date.getEndTime()));
			}
			num++;
		}
		if(page != null){
			if(num==1){
				url.append("?"+"pageNum="+page.getPageNum());
				url.append("&"+"pageSize="+page.getPageSize());
			}else{
				url.append("&"+"pageNum="+page.getPageNum());
				url.append("&"+"pageSize="+page.getPageSize());
			}
		}
	}
	
	/**
	 * 2016.1212 dzq 链接与参数拼接
	 * @param url
	 * @param map
	 */
	public void urlFormat(StringBuffer url,String element){
		url.append("?"+element);
	}
	
	/**
	 * 12.13dzq 增加请求返回String 取值方法
	 * @param result http返回数据
	 * @param key 取数据的键
	 * @return
	 */
	public Object numberResultJsonFormat(String result,String key){
		if(result==null)
			return 0;
		JSONObject js=new JSONObject(result);
		return "null".equals(js.get(key).toString())?0:js.get(key).toString();
	}
	
	@SuppressWarnings("unchecked")
	public Object numberResultJsonFormatList(String result,String key){
		if(result==null)
			return 0;
		JSONObject js=new JSONObject(result);
		JSONObject data=new JSONObject(js.get(key).toString());
		
		Iterator<String> ite=data.keys();
		Map<String, Object> map=new HashMap<String, Object>();
		while(ite.hasNext()){
			String keyNow=ite.next();
			map.put(keyNow, "null".equals(data.get(keyNow).toString())?0:data.get(keyNow).toString());
		}
		return map;
	}
	
	public Object resultJsonFormat(String result,String... key){
		if(result==null)
			return 0;
		JSONObject js=new JSONObject(result);
		for(int i=0;i<key.length-1;i++){
			Object now=js.get(key[i]);
			String nowString=now.toString();
			if("[]".equals(nowString))
				return "";
			js=new JSONObject(nowString);
		}
		Object res=js.get(key[key.length-1]);
		if("[]".equals(res.toString())){;
			return "";
		}
		return res;
	} 
	
	
	/**
	 * 12.16dzq 增加自动匹配json参数装箱方法
	 * @param obj 想装入的javabean
	 * @param result 查询返回的json串
	 * @param key json key
	 * @return
	 * @throws Exception
	 */
	/*public <T> int javaBeanOrSet(T obj,JSONObject js)throws Exception{
		if(js==null)
			return 0;
		Class tClass = obj.getClass();
		//获得该类的所有属性
		Field[] fields = tClass.getDeclaredFields();
		for(Field field:fields){
			Iterator<String> ite=js.keys();
			PropertyDescriptor pd = new PropertyDescriptor(field.getName(), tClass);
			//获得set方法
			Method method = pd.getWriteMethod();
			String fieldName = field.getName();
			while(ite.hasNext()){
				String next=ite.next();
				if(fieldName.equals(next)){
					if(js.get(next).getClass()==field.getType()){
						method.invoke(obj, new Object[]{js.get(next)});
					}
					System.out.println(js.get(next).getClass());
					System.out.println(field.getClass());
					System.out.println(field.getType());
						method.invoke(obj, new Object[]{(js.get(next))});
					continue;
				}
			}
		}
		return 1;
	}*/
	
}
